<?php
/**
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package default
* @subpackage lib
* @author Aljaz Srebrnic <a2piratesoft@gmail.com>;
* @author E. Pavletič
* @copyright 2008 a2PirateSoftware
* @license GPL License v3 <http://www.gnu.org/copyleft/gpl.html> */

require_once("ZNF/Actions/DispatchAction.php");
require_once('phpMailer/class.phpmailer.php');
require_once('Log.php');
require_once('class.Constants.php');
require_once('Pager/Pager.php');

class CommonAction extends ZNF_Actions_DispatchAction{


    protected $logger;
    protected $pager_options;

    public function __construct(){
        $this->logger = &Log::singleton(Constants::$handler, Constants::$name, '['.__CLASS__.']', Constants::$conf,Constants::$level);
	}

    /**
     * Metoda skrbi, da ni slucajno form izpolnjen avtomatsko.
     * Poslje tudi cookie z dvakrat sifriranim kljucem, vrne pa le
       enkrat-sifriran kljuc.
     * Ključ/žeton služi zato, da se onemogoči avtomatske prijave s strani t.i.
       'bot'-ov. Postopek je naslednji:
     *   1) strežnik generira ključ, ki ga pošlje odjemalcu/pregledovalniku.
         Ključ je sestavljen iz trenutnega
     *      TIMESTAMP in identifikatorja seje (SESSION). Strežnik pošlje ključ
            odjemalcu dvakrat in sicer:
     *      a) v obliki cookie-ja. V tem primeru ga bo spremenil tako, da bo
            dvakrat izračunal njegov md5 - md5(md5(ključ))
     *      b) v obliki skritega polja v obrazcu za registracijo. V tem slučaju
            ga bo spremenil z enim samim
     *         izračunom md5 - md5(ključ). Tako spremenjeno vrednost ključa bo
               poslal odjemalcu v atributu 'name'
     *         skritega polja z id="key" (<input type="hidden" id="key"
               name="ključ" value="" />). Na odjemalčevi
     *         strani bo koda v javascriptu premaknila vrednost iz atributa
               'name' v atribut 'value' in istočasno
     *         kopirala vrednost identifikatorja skritega polja (id="key") v
               atribut 'name'.
     * Veljavnost (rok trajanja) cookie-ja določa konstanta razreda
       COOKIE_EXPIRE_TIME.
     * Ko dobi strežnik podatke obrazca za registracijo najprej poišče vrednost
       polja z identifikatorjem id="key", jo
     * spremeni tako, da izračuna njen md5 in končno jo primerja z vrednostjo
       cookie-ja. V primeru, da sta vrednosti
     * enaki, zaključi postopek, sicer vrne napako
     *
     * @return kljuc, sifriran z metodo md5. */


    public static function sendToken() {
        $now = mktime();
        $key = $now.session_id();
        $md5Key = md5($key);
        // Pošlje cookie
            setcookie('tbtoken', md5($md5Key), $now+Constants::$COOKIE_EXPIRE_TIME);
        return $md5Key;
    }

    public static function sendLoginToken() {
        $now = mktime();
        $key = $now . session_id();
        $md5Key = md5($key);
        // Pošlje cookie
            setcookie('loginToken', md5($md5Key));
        return $md5Key;
    }

    /**
     *Metoda poslje dan email na dan naslov.
     *
     */
    public function sendEmail($name, $surname, $email, $subject, $body) {
        // Creates a new mailer
        $mailer = new PHPMailer();
        $mailer->Mailer = Constants::$mailer;
        // charset
        $mailer->CharSet = Constants::$charset;
        // content type
        $mailer->ContentType = Constants::$contentType;
        // encoding
        $mailer->Encoding = Constants::$encoding;
        //body
        $mailer->Body = $body;

        $this->logger->debug('['.__METHOD__.':'.__LINE__.'] Initial configuration completed.');
        switch ($mailer->Mailer) {
            case 'sendmail':
                $mailer->Sendmail = $this->config->getSendmail;
                break;
            case 'smtp':
                $mailer->Host = Constants::$host;
                $mailer->Port = Constants::$port;
                if (Constants::$smtpAuth == true) { //Whether or not to use SMTP authentication
                    $mailer->Username = Constants::$username;
                    $mailer->Password = Constants::$password;
        }
        $mailer->Hostname = Constants::$hostname; // The value to give when sending EHLO or HELO
        if (Constants::$timeout !== null)
            $mailer->Timeout = intval(Constants::$timeout);
        $mailer->SMTPKeepAlive = Constants::$smtpKeepAlive; //Indicate whether or not the SMTP connection should persist over multiple calls to the send() method
        $mailer->SMTPDebug = Constants::$smtpDebug; //Whether to enable SMTP debug mode or not break;
        }
        $this->logger->debug('['.__METHOD__.':'.__LINE__.'] Host & port configured.');
        // Sends the registration confirmation email
        $mailer->From = Constants::$from; // From:
        if (Constants::$fromName !== null) // From name:
            $mailer->FromName = Constants::$fromName;
        $mailer->AddAddress($email, $name . $surname); // To:
        $mailer->Subject = $subject;
        $this->logger->debug('['.__METHOD__.':'.__LINE__.'] Subject, To and From set.');
        if (Constants::$cc !== null)
        { // CC:
            $recipients = explode(',', Constants::$cc);
            foreach($recipients as $recipient) {
                $tokens = explode( '-', $recipient); $address = trim($tokens[0]);
                $name = '';
                if (isset($tokens[1]))
                    $name = trim($tokens[1]);
                $mailer->AddCC($address, $name);
            }
        }
        if (Constants::$bcc !== null)
        { // BCC:
            $recipients = explode(',', Constants::$bcc);
            foreach($recipients as $recipient) {
                $tokens = explode( '-', $recipient); $address = trim($tokens[0]);
                $name = '';
                if (isset($tokens[1]))
                    $name = trim($tokens[1]);
                $mailer->AddBCC($address, $name);
            }
        }
        if (Constants::$replyTo !== null) // Return-Path:
            $mailer->AddReplyTo(Constants::$replyTo);

        if (!$mailer->Send()) {
            throw new ZNF_Action_ActionException('errorEmailSend - ' . $mailer->ErrorInfo);
       }

    }
    /**
     *Metoda za generiranje random gesla. Dobil na internetu: http://snippets.dzone.com/posts/show/1487.
    */
    public function generatePassword() {
	// Create the meta-password
	$sMetaPassword = "";

        $ahPasswordGenerator = array(
                        "C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => 4, 'maximum' => 8),
                        "S" => array('characters' => "!@()-_=+?*^", 'minimum' => 1, 'maximum' => 3),
                        "N" => array('characters' => '1234567890', 'minimum' => 2, 'maximum' => 3)
        );

	foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
		$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));

	$sMetaPassword = str_shuffle($sMetaPassword);

	// Create the real password
	$arBuffer = array();
	for ($i = 0; $i < strlen($sMetaPassword); $i ++)
		$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];

	return implode("", $arBuffer);
    }

    public static function handleException($e, $module){
        $logger = &Log::singleton(Constants::$handler, Constants::$name, '['.__CLASS__.']', Constants::$conf,Constants::$level);
        $translation = new ZNF_Presentation_Translation($module, $_SESSION['znf']['lang']);
        $error = new ZNF_Action_ActionErrors();

        $logger->err($e->getMessage());
        $queryString = explode('-' ,$e->getMessage());
        $error->addError(1, $translation->get(trim($queryString[0])));
        return $error;
    }


    /**
     * Metoda ustvari pager.
     * @return Pager Nov pager.
     **/

    public function getPagerLinks($total, $module, $action, $params = ''){
		$translation = new ZNF_Presentation_Translation(null, $_SESSION['znf']['lang']);

		$pager_options = array(	'mode' => Constants::$pagingMode,
					'perPage' => Constants::$limit,
					'delta' => Constants::$delta,
					'altPrev' => $translation->get('pagerPrevAlt'),
					'altNext' => $translation->get('pagerNextAlt'),
					'altPage' => $translation->get('pagerPageAlt'),
					/*'linkClass' => 'button',*/
					'append' => false,
					'curPageLinkClassName' => 'curPage',
					'totalItems' => $total,
					'urlVar' => 'pageID',
					'fileName' => "?znfModule=$module&znfAction=$action$params&pageID=%d");
		$pager = Pager::factory($pager_options);
		$links = $pager->getLinks();
		return $links['all'];
    }

}

?>